<template>
  <el-button v-bind="$props"
             v-on="listeners"
             :loading="isThrottle && loading"
             @click="handleClick">
    <slot></slot>
  </el-button>
</template>

<script>
import { Button } from 'element-ui'
import { omit } from 'lodash'
export default {
  name: 'ThrottleButton',
  props: {
    ...omit(Button.props, 'loading'),
    isThrottle: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      loading: false
    }
  },
  computed: {
    listeners () {
      return omit(this.$listeners, 'click')
    }
  },
  methods: {
    handleClick () {
      this.loading = true
      let count = 0
      let isDone = false
      let timer = null
      let done = () => {
        if (count >= 2) {
          this.loading = false
          clearInterval(timer)
          return
        }
        isDone = true
      }

      timer = setInterval(() => {
        ++count

        isDone && done()
      }, 1000)

      try {
        this.$emit('event:throttle-click', done, this.$props)
      } catch (error) {
        done()
      }
    }
  }
}
</script>
